import { getImageUrl, sms, doRegist } from "../../utils/interface";
import Notify from "@vant/weapp/notify/notify";
Page({
  data: {
    imageUrl: "",
    mobile: "",
    pwd: "",
    repwd: "",
    nick: "",
    region: [],
    picCode: "", //图形验证码
    code: "", //短信验证码
    key: "",
    error: {
      mobile: "",
      pwd: "",
      repwd: "",
      nick: "",
      picCode: "", //图形验证码
      code: "", //短信验证码
    },
    isPwd: false, //false 闭眼；true 睁眼
    seconds: "", //倒计时的内容
  },
  onLoad() {
    this.getImage();
  },
  //获取验证码
  getImage() {
    let key = Date.now();
    this.data.key = key;
    let result = getImageUrl({ key: key });
    this.setData({
      imageUrl: result,
    });
  },
  //获取短信验证码
  async getsms() {
    //顶部错误提示
    let message = "";
    if (!/^1[3-9]\d{9}$/.test(this.data.mobile)) {
      message = "手机号格式不正确";
    } else if (this.data.picCode.length !== 6) {
      message = "请输入验证码";
    }
    if (message !== "") {
      Notify(message);
      return;
    }
    let obj = {
      mobile: this.data.mobile,
      picCode: this.data.picCode,
      key: this.data.key,
    };
    let {data:res} = await sms(obj);
    //如果验证码不正确，顶部提示用户
    if(res.code!==0){
      Notify(res.msg)
    }

    //倒计时
    this.data.seconds = 60;

    this.data.seconds -= 1;
    this.setData({
      seconds: this.data.seconds,
    });

    let timer = setInterval(() => {
      this.data.seconds -= 1;
      if (this.data.seconds == 0) {
        this.setData({
          seconds: "",
        });
        clearInterval(timer);
        return;
      }
      this.setData({
        seconds: this.data.seconds,
      });
    }, 1000);
  },
  //点击注册按钮
  async handleRegist() {
    //1. 验证表单
    this.data.error = {};
    let tag = true;
    if (!/^1[3-9]\d{9}$/.test(this.data.mobile)) {
      this.data.error.mobile = "手机号格式错误";
      tag = false;
    } else if (!/^\w{6,16}$/.test(this.data.pwd)) {
      this.data.error.pwd = "密码长度在6-16之间";
      tag = false;
    } else if (this.data.pwd !== this.data.repwd) {
      this.data.error.repwd = "重复密码和密码不相等";
      tag = false;
    } else if (this.data.nick.length == 0) {
      this.data.error.nick = "请输入用户名";
      tag = false;
    } else if (this.data.picCode.length == 0) {
      this.data.error.picCode = "请输入图形验证码";
      tag = false;
    } else if (this.data.code.toString().length !== 4) {
      this.data.error.code = "请输入短信验证码";
      tag = false;
    }

    this.setData({
      error: this.data.error,
    });

    if (!tag) return;

    //2.进行注册（请求接口）
    let { mobile, pwd, code, nick } = this.data;

    let { data: res } = await doRegist({ mobile, pwd, code, nick }).catch(
      (err) => err
    );
  },
  //点击密码眼睛
  pwdClick() {
    this.data.isPwd = !this.data.isPwd;
    this.setData({
      isPwd: this.data.isPwd,
    });
  },
});
